{%- set class = (class ?? [])|explodeClass|merge([
    'select',
    (disabled ?? false) ? 'disabled' : null,
]|filter) %}

{%- set options = options ?? [] %}
{%- set value = value ?? null %}
{%- set hasOptgroups = false -%}

{%- set containerAttributes = {
  class: class,
}|merge(containerAttributes ?? [], recursive=true) %}

{%- if block('attr') is defined %}
  {%- set containerAttributes = containerAttributes|merge(('<div ' ~ block('attr') ~ '>')|parseAttr, recursive=true) %}
{% endif %}

{% set inputAttributes = {
  id: id ?? false,
  class: [
    (toggle ?? false) ? 'fieldtoggle' : null,
  ]|filter,
  name: name ?? false,
  autofocus: (autofocus ?? false) and not craft.app.request.isMobileBrowser(true),
  disabled: disabled ?? false,
  data: {
    'target-prefix': (toggle ?? false) ? (targetPrefix ?? '') : false,
  },
}|merge(inputAttributes ?? [], recursive=true) %}

<div {{ attr(containerAttributes) }}>
    <select {{ attr(inputAttributes) }}>
        {% for key, option in options %}
            {% if option.optgroup is defined %}
                {% if hasOptgroups %}
                    </optgroup>
                {% else %}
                    {% set hasOptgroups = true %}
                {% endif %}
                <optgroup label="{{ option.optgroup }}">
            {% else %}
                {% set optionLabel = (option.label is defined ? option.label : option) %}
                {% set optionValue = (option.value is defined ? option.value : key) %}
                {% set optionDisabled = (option.disabled is defined ? option.disabled : false) %}
                <option value="{{ optionValue }}"{% if (optionValue~'') is same as (value~'') %} selected{% endif %}{% if optionDisabled %} disabled{% endif %}>{{ optionLabel }}</option>
            {% endif %}
        {% endfor %}
        {% if hasOptgroups %}
            </optgroup>
        {% endif %}
    </select>
</div>
